﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace ANGF
{
    public partial class FormWebAuth : Form
    {
        private Action<string> doneNotifyProc;
        public FormWebAuth(Action<string> doneNotifyProc)
        {
            this.doneNotifyProc = doneNotifyProc;
            InitializeComponent();
        }

        private void FormWebAuth_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://angfwebplayer4.azurewebsites.net/Account/LoginOA");
        }

        internal string AccessToken = null;
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            AccessToken = null;
            Close();
        }

        private void FormWebAuth_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (doneNotifyProc != null) doneNotifyProc(AccessToken);
        }

        private Uri keepuri;
        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (e.Url == keepuri)
            {
                this.webBrowser1.Show();
                this.Cursor = Cursors.Default;
                keepuri = null;
            }
        }
        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            if (e.Url.ToString().ToLower().EndsWith("loginoa"))
            {
                keepuri = e.Url;
                this.webBrowser1.Hide();
                this.Cursor = Cursors.WaitCursor;
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var ar = webBrowser1.Document.Cookie.Split(';').Select(c =>
            {
                int Idx = c.IndexOf("=");
                if (Idx > 0)
                {
                    var CookieName = c.Substring(0, Idx).Trim();
                    var CookieValue = c.Substring(Idx + 1).Trim();
                    return new Tuple<string, string>(CookieName, CookieValue);
                }
                else
                {
                    return null;
                }
            }).Where(c => c != null);
            var r = ar.FirstOrDefault(c => c.Item1 == /*".AspNet.Cookies"*/".AspNet.ApplicationCookie");
            if (r != null)
            {
                AccessToken = r.Item2;
                Close();
            }
        }

    }
}
